package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @ClassName seckillProductJob
 * @Author VCR
 * @Date 2021/12/30 23:51
 * @Version 1.0
 */
@Component // 交给Spring容器管理
@Getter
@Setter
public class SeckillProductJob implements SimpleJob {
    // 实现SimpleJob 模仿UserCacheJob实现

    // 模仿cron 修改nacos的文件
    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;  // 注入feign

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void execute(ShardingContext shardingContext) {

//        System.out.println("avCoder");
//        // 开启三个线程 3次
//        System.out.println(new Date() +"分片参数:"+shardingContext.getShardingParameter());

        // 远程调用秒杀服务把数据查询出来
        /**
         * 秒杀服务挂了 返回值为null
         * 内部出现异常 {code:50100,msg:"xxx"}
         * 都没问题{code:200}
         */

        // 定时任务服务
        String time = shardingContext.getShardingParameter();
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTime(Integer.parseInt(time));

        if (result != null && !result.hasError()) {
            List<SeckillProductVo> data = result.getData();
            if (data != null && data.size() > 0) {
                // 把数据放在redis中
                // seckillProduct:time value中:key seckillId/SeckillProductVO
                for (SeckillProductVo seckillProductVo : data) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));

                    // key seckillStockCount:time value=>key:seckillId,value:count
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");
                }

                System.out.println("同步成功"+time);
            }
        }
        // 把数据放到redis中

    }
}
